package com.jsh.erp.service.depotItem;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.datasource.vo.DepotHeadVo4List;
import com.jsh.erp.datasource.vo.DepotItemStockWarningCount;
import com.jsh.erp.datasource.vo.DepotItemVo4Stock;
import com.jsh.erp.datasource.vo.DepotItemVoBatchNumberList;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.depot.DepotService;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.materialExtend.MaterialExtendService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.material.MaterialService;
import com.jsh.erp.service.rebate.RebateService;
import com.jsh.erp.service.serialNumber.SerialNumberService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.IdUtils;
import com.jsh.erp.utils.QueryUtils;
import com.jsh.erp.utils.StringUtil;
import com.jsh.erp.utils.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.jsh.erp.utils.Tools.getCenternTime;

@Service
public class DepotItemService {
    private Logger logger = LoggerFactory.getLogger(DepotItemService.class);

    private final static String TYPE = "入库";
    private final static String SUM_TYPE = "number";
    private final static String IN = "in";
    private final static String OUT = "out";

    @Resource
    private DepotItemMapper depotItemMapper;
    @Resource
    private DepotItemMapperEx depotItemMapperEx;
    @Resource
    private MaterialService materialService;
    @Resource
    private MaterialExtendService materialExtendService;
    @Resource
    private SerialNumberMapperEx serialNumberMapperEx;
    @Resource
    private DepotHeadService depotHeadService;
    @Resource
    private DepotHeadMapper depotHeadMapper;
    @Resource
    private SerialNumberService serialNumberService;
    @Resource
    private UserService userService;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private MaterialCurrentStockMapper materialCurrentStockMapper;
    @Resource
    private MaterialInitialStockMapper materialInitialStockMapper;
    @Resource
    private MaterialMapper materialMapper;
    @Resource
    private MaterialExtendMapper materialExtendMapper;
    @Resource
    private LogService logService;
    @Resource
    private DepotService depotService;
    @Resource
    private RebateService rebateService;
    @Resource
    private SynchronizationTaskMapperEx synchronizationTaskMapperEx;
    @Resource
    private MaterialCurrentStockMapperEx materialCurrentStockMapperEx;

    public DepotItem getDepotItem(String id) throws Exception {
        DepotItem result = null;
        try {
            result = depotItemMapper.selectByPrimaryKey(id);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotItem> getDepotItem() throws Exception {
        DepotItemExample example = new DepotItemExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotItem> list = null;
        try {
            list = depotItemMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<DepotItem> select(String name, Integer type, String remark, int offset, int rows) throws Exception {
        List<DepotItem> list = null;
        try {
            list = depotItemMapperEx.selectByConditionDepotItem(name, type, remark, offset, rows);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public Long countDepotItem(String name, Integer type, String remark) throws Exception {
        Long result = null;
        try {
            result = depotItemMapperEx.countsByDepotItem(name, type, remark);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertDepotItem(JSONObject obj, HttpServletRequest request) throws Exception {
        DepotItem depotItem = JSONObject.parseObject(obj.toJSONString(), DepotItem.class);
        int result = 0;
        try {
            depotItem.setUploadFlag("0");
            result = depotItemMapper.insertSelective(depotItem);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateDepotItem(JSONObject obj, HttpServletRequest request) throws Exception {
        DepotItem depotItem = JSONObject.parseObject(obj.toJSONString(), DepotItem.class);
        int result = 0;
        try {
            depotItem.setUploadFlag("0");
            result = depotItemMapper.updateByPrimaryKeySelective(depotItem);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteDepotItem(String id, HttpServletRequest request) throws Exception {
        return batchDeleteDepotItemIds(id);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDepotItem(String ids, HttpServletRequest request) throws Exception {
        return batchDeleteDepotItemIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDepotItemIds(String ids) throws Exception {
        String[] idArray = ids.split(",");
        User userInfo = userService.getCurrentUser();
        int result = 0;
        try {
            result = depotItemMapperEx.batchDeleteDepotItemByIds(new Date(), userInfo == null ? null : userInfo.getId(), idArray);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public int checkIsNameExist(String id, String name) throws Exception {
        DepotItemExample example = new DepotItemExample();
        example.createCriteria().andIdNotEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotItem> list = null;
        try {
            list = depotItemMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list == null ? 0 : list.size();
    }

    public List<DepotItemVo4DetailByTypeAndMId> findDetailByDepotIdsAndMaterialIdList(List<String> depotList, String sku, String mId, int offset, int rows) throws Exception {
        List<DepotItemVo4DetailByTypeAndMId> list = null;
        try {
            list = synchronizationTaskMapperEx.findDetailByDepotIdsAndMaterialIdList(depotList, sku, mId, offset, rows);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    private List<String> parseListByDepotIds(String depotIds) throws Exception {
        List<String> depotList = new ArrayList<>();
        if(StringUtil.isNotEmpty(depotIds)) {
            depotList = StringUtil.strToStringList(depotIds);
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = depotService.findDepotByCurrentUser();
            for(Object obj: depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getString("id"));
            }
            //如果有权限的仓库数量太多则提示要选择仓库
            if(depotList.size()>100) {
                throw new BusinessRunTimeException(ExceptionConstants.REPORT_TWO_MANY_DEPOT_FAILED_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.REPORT_TWO_MANY_DEPOT_FAILED_MSG :  ExceptionConstants.REPORT_TWO_MANY_DEPOT_FAILED_MSG_US);
            }
        }
        return depotList;
    }

    public Long findDetailByDepotIdsAndMaterialIdCount(List<String> depotList, String sku, String mId) throws Exception {
        Long result = null;
        try {
            result = synchronizationTaskMapperEx.findDetailByDepotIdsAndMaterialIdCount(depotList, sku, mId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotItemVo4DetailByTypeAndMId> findByMaterialAll(String materialId, Integer offset, Integer rows) throws Exception {
        List<DepotItemVo4DetailByTypeAndMId> list = null;
        try {
            list = depotItemMapperEx.findByMaterialAll(materialId, offset, rows);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public int findByMaterialAllCount(String materialId) throws Exception {
        int result = 0;
        try {
            result = depotItemMapperEx.findByMaterialAllCount(materialId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertDepotItemWithObj(DepotItem depotItem) throws Exception {
        int result = 0;
        try {
            depotItem.setId(IdUtils.getUUID());
            depotItem.setUploadFlag("0");
            result = depotItemMapper.insertSelective(depotItem);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateDepotItemWithObj(DepotItem depotItem) throws Exception {
        int result = 0;
        try {
            depotItem.setUploadFlag("0");
            result = depotItemMapper.updateByPrimaryKeySelective(depotItem);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotItem> getListByHeaderId(String headerId) throws Exception {
        List<DepotItem> list = null;
        try {
            DepotItemExample example = new DepotItemExample();
            example.createCriteria().andHeaderIdEqualTo(headerId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = depotItemMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    /**
     * 查询当前单据中指定商品的明细信息
     *
     * @param headerId
     * @param meId
     * @return
     * @throws Exception
     */
    public DepotItem getItemByHeaderIdAndMaterial(String headerId, String meId) throws Exception {
        DepotItem depotItem = new DepotItem();
        try {
            DepotItemExample example = new DepotItemExample();
            example.createCriteria().andHeaderIdEqualTo(headerId).andMaterialExtendIdEqualTo(meId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<DepotItem> list = depotItemMapper.selectByExample(example);
            if (list != null && list.size() > 0) {
                depotItem = list.get(0);
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return depotItem;
    }

    /**
     * 查询被关联订单中指定商品的明细信息
     *
     * @param linkNumber
     * @param meId
     * @return
     * @throws Exception
     */
    public DepotItem getPreItemByHeaderIdAndMaterial(String linkNumber, String meId, String linkId) throws Exception {
        DepotItem depotItem = new DepotItem();
        try {
            DepotHead depotHead = depotHeadService.getDepotHead(linkNumber);
            DepotItemExample example = new DepotItemExample();
            example.createCriteria().andHeaderIdEqualTo(depotHead.getId()).andMaterialExtendIdEqualTo(meId).andIdEqualTo(linkId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<DepotItem> list = depotItemMapper.selectByExample(example);
            if (list != null && list.size() > 0) {
                depotItem = list.get(0);
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return depotItem;
    }

    public List<DepotItemVo4WithInfoEx> getDetailList(String headerId) throws Exception {
        List<DepotItemVo4WithInfoEx> list = null;
        try {
            list = depotItemMapperEx.getDetailList(headerId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<DepotItemVo4WithInfoEx> getHeadDetailList(String headerId) throws Exception {
        List<DepotItemVo4WithInfoEx> list = null;
        try {
            list = synchronizationTaskMapperEx.getHeadDetailList(headerId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<DepotItemVo4WithInfoEx> getDetailListByCustom11(String headerId) throws Exception {
        List<DepotItemVo4WithInfoEx> list = null;
        try {
            list = depotItemMapperEx.getDetailListByCustom11(headerId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<DepotItemVo4WithInfoEx> findByAll(String materialParam, String endTime, Integer offset, Integer rows) throws Exception {
        List<DepotItemVo4WithInfoEx> list = null;
        try {
            list = depotItemMapperEx.findByAll(materialParam, endTime, offset, rows);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public int findByAllCount(String materialParam, String endTime) throws Exception {
        int result = 0;
        try {
            result = depotItemMapperEx.findByAllCount(materialParam, endTime);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotItemVo4WithInfoEx> getListWithBugOrSale(String materialParam, String billType, String beginTime, String endTime,
                                                             Integer offset, Integer rows,String depotId,List<String> idList) throws Exception {
        List<DepotItemVo4WithInfoEx> list = null;
        try {
            list = depotItemMapperEx.getListWithBugOrSale(materialParam, billType, beginTime, endTime, offset, rows,depotId,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public int getListWithBugOrSaleCount(String materialParam, String billType, String beginTime, String endTime,String depotId,List<String> idList) throws Exception {
        int result = 0;
        try {
            result = depotItemMapperEx.getListWithBugOrSaleCount(materialParam, billType, beginTime, endTime,depotId,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public BigDecimal buyOrSale(String type, String subType, String MId, String beginTime, String endTime, String sumType,
                                String type1,String subType1,String depotId,List<String> idList) throws Exception {
        BigDecimal result = BigDecimal.ZERO;
        try {
            if (SUM_TYPE.equals(sumType)) {
                result = depotItemMapperEx.buyOrSaleNumber(type, subType, MId, beginTime, endTime, sumType,type1,subType1,depotId,idList);
            } else {
                result = depotItemMapperEx.buyOrSalePrice(type, subType, MId, beginTime, endTime, sumType,type1,subType1,depotId);
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;

    }

    public List<DepotItemVoDetailByMId> buyDetailList(String type, String subType, String MId, String beginTime, String endTime,
                                                      Integer offset, Integer rows,String type1,String subType1) throws Exception {
        List<DepotItemVoDetailByMId> result = null;
        try {
//            List<String> typeList = StringUtil.strToStringList(type);
//            List<String> subTypeList = StringUtil.strToStringList(subType);
            result = depotItemMapperEx.buyDetailList(type, subType, MId, beginTime, endTime, offset, rows,type1,subType1);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;

    }

    /**
     * 统计采购或销售的总金额
     *
     * @param type
     * @param subType
     * @param month
     * @return
     * @throws Exception
     */
    public BigDecimal inOrOutPrice(String type, String subType, String month, String type1, String subType1) throws Exception {
        BigDecimal result = BigDecimal.ZERO;
        try {
            String beginTime = Tools.firstDayOfMonth(month) + BusinessConstants.DAY_FIRST_TIME;
            String endTime = Tools.lastDayOfMonth(month) + BusinessConstants.DAY_LAST_TIME;
            result = depotItemMapperEx.inOrOutPrice(type, subType, beginTime, endTime, type1, subType1);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    /**
     * 统计零售的总金额
     *
     * @param type
     * @param subType
     * @param month
     * @return
     * @throws Exception
     */
    public BigDecimal inOrOutRetailPrice(String type, String subType, String month, String type1, String subType1) throws Exception {
        BigDecimal result = BigDecimal.ZERO;
        try {
            String beginTime = Tools.firstDayOfMonth(month) + BusinessConstants.DAY_FIRST_TIME;
            String endTime = Tools.lastDayOfMonth(month) + BusinessConstants.DAY_LAST_TIME;
            result = depotItemMapperEx.inOrOutRetailPrice(type, subType, beginTime, endTime, type1, subType1);
            result = result.abs();
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }
    public BigDecimal inOrOutRetailMoney(String month) throws Exception {
        BigDecimal result = BigDecimal.ZERO;
        try {
            String beginTime = Tools.firstDayOfMonth(month) + BusinessConstants.DAY_FIRST_TIME;
            String endTime = Tools.lastDayOfMonth(month) + BusinessConstants.DAY_LAST_TIME;
            result = depotItemMapperEx.inOrOutRetailMoney(beginTime, endTime);
            result = result.abs();
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void saveDetials(String rows, String headerId, String actionType, HttpServletRequest request, boolean flag) throws Exception {
        //查询单据主表信息
        DepotHead depotHead = depotHeadMapper.selectByPrimaryKey(headerId);
        //删除单据的明细
        deleteDepotItemHeadId(headerId);
        JSONArray rowArr = JSONArray.parseArray(rows);
        Map<String, String> depotIdMap = new HashMap<>();
        Map<String, Map<String, Object>> linkIdMap = new HashMap<>();
        BigDecimal rebateAllAmount=BigDecimal.ZERO;
        if (null != rowArr && rowArr.size() > 0) {
            for (int i = 0; i < rowArr.size(); i++) {
                DepotItem depotItem = new DepotItem();
                JSONObject rowObj = JSONObject.parseObject(rowArr.getString(i));
                depotItem.setHeaderId(headerId);
                String meId = rowObj.getString("meId");
//                String materialId = rowObj.getString("materialId");
                if (StringUtils.isEmpty(meId)) {
                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_MEID_EMPTY_CODE,
                            String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_MEID_EMPTY_MSG : ExceptionConstants.MATERIAL_MEID_EMPTY_MSG_US));
                }
                MaterialExtend materialExtend = materialExtendService.getInfoByMeId(meId);
                depotItem.setMaterialId(materialExtend.getMaterialId());
                depotItem.setMaterialExtendId(materialExtend.getId());
                depotItem.setMaterialUnit(rowObj.getString("unit"));

                if (StringUtil.isExist(rowObj.get("snList"))) {
                    depotItem.setSnList(rowObj.getString("snList"));
                    if (StringUtil.isExist(rowObj.get("depotId"))) {
                        String depotId = rowObj.getString("depotId");
                        serialNumberService.addSerialNumberByBill(depotHead.getType(), depotHead.getSubType(),
                                depotHead.getNumber(), materialExtend.getMaterialId(), depotId, depotItem.getSnList());
                    }
                }
                if (StringUtil.isExist(rowObj.get("batchNumber"))) {
                    depotItem.setBatchNumber(rowObj.getString("batchNumber"));
                }
                if (StringUtil.isExist(rowObj.get("expirationDate"))) {
                    depotItem.setExpirationDate(rowObj.getDate("expirationDate"));
                }
                if (StringUtil.isExist(rowObj.get("sku"))) {
                    depotItem.setSku(rowObj.getString("sku"));
                }
                if (("下达采购".equals(depotHead.getSubType()) || "收费确认".equals(depotHead.getSubType())) && flag) {
                    depotItem.setLinkId(rowObj.getString("id"));
                } else if (StringUtil.isExist(rowObj.get("linkId"))) {
                    depotItem.setLinkId(rowObj.getString("linkId"));
                }
                //以下进行单位换算
                Unit unitInfo = materialService.findUnit(materialExtend.getMaterialId()); //查询计量单位信息
                if (StringUtil.isExist(rowObj.get("operNumber"))) {
                    BigDecimal operNumber = rowObj.getBigDecimal("operNumber");
                    if (operNumber.compareTo(BigDecimal.ZERO) > 0 || "盘点单".equals(depotHead.getSubType())) {
                        depotItem.setOperNumber(operNumber);
                    } else {
                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_NUMBER_ZERO_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_NUMBER_ZERO_MSG : ExceptionConstants.DEPOT_HEAD_NUMBER_ZERO_MSG_US, i + 1));
                    }
                    String unit = rowObj.get("unit").toString();
                    BigDecimal oNumber = rowObj.getBigDecimal("operNumber");
                    if (StringUtil.isNotEmpty(unitInfo.getName())) {
                        String basicUnit = unitInfo.getBasicUnit(); //基本单位
                        if (unit.equals(basicUnit)) { //如果等于基本单位
                            depotItem.setBasicNumber(oNumber); //数量一致
                        } else if (unit.equals(unitInfo.getOtherUnit())) { //如果等于副单位
                            depotItem.setBasicNumber(oNumber.multiply(new BigDecimal(unitInfo.getRatio()))); //数量乘以比例
                        } else if (unit.equals(unitInfo.getOtherUnitTwo())) { //如果等于副单位2
                            depotItem.setBasicNumber(oNumber.multiply(new BigDecimal(unitInfo.getRatioTwo()))); //数量乘以比例
                        } else if (unit.equals(unitInfo.getOtherUnitThree())) { //如果等于副单位3
                            depotItem.setBasicNumber(oNumber.multiply(new BigDecimal(unitInfo.getRatioThree()))); //数量乘以比例
                        } else {
                            depotItem.setBasicNumber(oNumber); //其他情况
                        }
                    } else {
                        depotItem.setBasicNumber(oNumber); //其他情况
                    }
                }
                //如果数量+已完成数量>原订单数量，给出预警(判断前提是存在关联订单)
                if (StringUtil.isNotEmpty(depotHead.getLinkNumber()) && !"厂家报价".equals(depotHead.getSubType())
                        && !"直发厂家报价".equals(depotHead.getSubType())
                        && StringUtil.isExist(rowObj.get("preNumber")) && StringUtil.isExist(rowObj.get("finishNumber"))) {
                    if ("add".equals(actionType)) {
                        //在新增模式进行状态赋值
                        BigDecimal preNumber = rowObj.getBigDecimal("preNumber");
                        BigDecimal finishNumber = rowObj.getBigDecimal("finishNumber");
                        if (depotItem.getOperNumber().add(finishNumber).compareTo(preNumber) > 0) {
                            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_CODE,
                                    String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_MSG_US));
                        }
                    } else if ("update".equals(actionType)) {
                        //在更新模式进行状态赋值
                        String unit = rowObj.get("unit").toString();
                        String preHeaderId = depotHeadService.getDepotHead(depotHead.getLinkNumber()).getId();
                        //前一个单据的数量
                        BigDecimal preNumber = getPreItemByHeaderIdAndMaterial(depotHead.getLinkNumber(), depotItem.getMaterialExtendId(), depotItem.getLinkId()).getOperNumber();
                        //除去此单据之外的已入库|已出库
                        BigDecimal realFinishNumber = getRealFinishNumber(depotItem.getMaterialExtendId(), depotItem.getLinkId(), preHeaderId, headerId, unitInfo, unit);
                        if (depotItem.getOperNumber().add(realFinishNumber).compareTo(preNumber) > 0) {
                            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_CODE,
                                    String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_MSG_US));
                        }
                    }
                }
                if (StringUtil.isExist(rowObj.get("unitPrice"))) {
                    BigDecimal unitPrice = rowObj.getBigDecimal("unitPrice");
                    depotItem.setUnitPrice(unitPrice);
                    if (materialExtend.getLowDecimal() != null) {
                        //零售或销售单价低于最低售价，进行提示
                        if ("零售".equals(depotHead.getSubType()) || "销售".equals(depotHead.getSubType())) {
                            if (unitPrice.compareTo(materialExtend.getLowDecimal()) < 0) {
                                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_UNIT_PRICE_LOW_CODE,
                                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_UNIT_PRICE_LOW_MSG : ExceptionConstants.DEPOT_HEAD_UNIT_PRICE_LOW_MSG_US));
                            }
                        }
                    }
                }
                if (StringUtil.isExist(rowObj.get("taxUnitPrice"))) {
                    depotItem.setTaxUnitPrice(rowObj.getBigDecimal("taxUnitPrice"));
                }
                if (StringUtil.isExist(rowObj.get("allPrice"))) {
                    depotItem.setAllPrice(rowObj.getBigDecimal("allPrice"));
                }
                if (StringUtil.isExist(rowObj.get("depotId"))) {
                    if ("厂家到货".equals(depotHead.getSubType())) {
                        depotIdMap.put(meId, rowObj.getString("depotId"));
                    }
                    depotItem.setDepotId(rowObj.getString("depotId"));
                } else {
                    if (!BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())
                            && !BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())
                            && !"要货申请".equals(depotHead.getSubType()) && !"配送".equals(depotHead.getSubType())
                            && !"验收".equals(depotHead.getSubType()) && !"补货申请".equals(depotHead.getSubType())
                            && !"厂家直发".equals(depotHead.getSubType()) && !"下达采购".equals(depotHead.getSubType())
                            && !"厂家到货".equals(depotHead.getSubType()) && !"收费确认".equals(depotHead.getSubType())
                            && !"厂家报价".equals(depotHead.getSubType()) && !"直发厂家报价".equals(depotHead.getSubType())
                            && !"直发销售退货".equals(depotHead.getSubType()) && !"直发采购退货".equals(depotHead.getSubType())
                    ) {
                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_DEPOT_FAILED_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_DEPOT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_DEPOT_FAILED_MSG_US));
                    }
                }
                if ("要货申请".equals(depotHead.getSubType()) || "配送".equals(depotHead.getSubType()) || "验收".equals(depotHead.getSubType())) {
                    if (depotHead.getDepotId().equals(depotHead.getAnotherDepotId())) {
                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ANOTHER_DEPOT_EQUAL_FAILED_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_ANOTHER_DEPOT_EQUAL_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_ANOTHER_DEPOT_EQUAL_FAILED_MSG_US));
                    } else {
                        depotItem.setDepotId(depotHead.getDepotId());
                        depotItem.setAnotherDepotId(depotHead.getAnotherDepotId());
                    }

                }

                if ("配送".equals(depotHead.getSubType()) && depotItem.getOperNumber().compareTo(depotItem.getBasicNumber()) == 1) {
                    throw new BusinessRunTimeException(8500019, "配送数不能大于要货数");
                }
                if ("验收".equals(depotHead.getSubType()) && depotItem.getOperNumber().compareTo(depotItem.getBasicNumber()) == 1) {
                    throw new BusinessRunTimeException(8500020, "验收数不能大于配送数");
                }
                if (StringUtil.isExist(rowObj.get("taxRate"))) {
                    depotItem.setTaxRate(rowObj.getBigDecimal("taxRate"));
                }
                if (StringUtil.isExist(rowObj.get("taxMoney"))) {
                    depotItem.setTaxMoney(rowObj.getBigDecimal("taxMoney"));
                }
                if (StringUtil.isExist(rowObj.get("taxLastMoney"))) {
                    depotItem.setTaxLastMoney(rowObj.getBigDecimal("taxLastMoney"));
                }
                if (StringUtil.isExist(rowObj.get("mType"))) {
                    depotItem.setMaterialType(rowObj.getString("mType"));
                }
                if (StringUtil.isExist(rowObj.get("remark"))) {
                    depotItem.setRemark(rowObj.getString("remark"));
                }
                if (StringUtil.isExist(rowObj.get("priceNote"))) {
                    if (!"null".equals(rowObj.getString("priceNote"))){
                        depotItem.setPriceNote(rowObj.getString("priceNote"));
                    }
                }
                if (StringUtil.isExist(rowObj.get("discountPrice"))) {
                    depotItem.setDiscountPrice(rowObj.getBigDecimal("discountPrice"));
                }
                if (StringUtil.isExist(rowObj.get("discountAllPrice"))) {
                    depotItem.setDiscountAllPrice(rowObj.getBigDecimal("discountAllPrice"));
                }
                if (StringUtil.isExist(rowObj.get("custom1"))) {
                    depotItem.setCustom1(rowObj.getString("custom1"));
                }
                if (StringUtil.isExist(rowObj.get("custom2"))) {
                    depotItem.setCustom2(rowObj.getString("custom2"));
                }
                if (StringUtil.isExist(rowObj.get("custom3"))) {
                    depotItem.setCustom3(rowObj.getString("custom3"));
                }
                if (StringUtil.isExist(rowObj.get("custom4"))) {
                    if (!"null".equals(rowObj.getString("custom4"))) {
                        depotItem.setCustom4(rowObj.getString("custom4"));
                    }
                }
                if (StringUtil.isExist(rowObj.get("custom5"))) {
                    depotItem.setCustom5(rowObj.getString("custom5"));
                }
                if (StringUtil.isExist(rowObj.get("custom6"))) {
                    depotItem.setCustom6(rowObj.getBigDecimal("custom6"));
                }
                if (StringUtil.isExist(rowObj.get("custom7"))) {
                    depotItem.setCustom7(rowObj.getBigDecimal("custom7"));
                }
                if (StringUtil.isExist(rowObj.get("custom8"))) {
                    depotItem.setCustom8(rowObj.getBigDecimal("custom8"));
                }
                if (StringUtil.isExist(rowObj.get("custom9"))) {
                    depotItem.setCustom9(rowObj.getBigDecimal("custom9"));
                }
                if (StringUtil.isExist(rowObj.get("custom10"))) {
                    depotItem.setCustom10(rowObj.getBigDecimal("custom10"));
                }
                if (StringUtil.isExist(rowObj.get("custom11"))) {
                    depotItem.setCustom11(rowObj.getInteger("custom11"));
                }
                if (StringUtil.isExist(rowObj.get("custom12"))) {
                    depotItem.setCustom12(rowObj.getInteger("custom12"));
                }
                if (StringUtil.isExist(rowObj.get("custom13"))) {
                    depotItem.setCustom13(rowObj.getInteger("custom13"));
                }
                if (StringUtil.isExist(rowObj.get("custom14"))) {
                    depotItem.setCustom14(rowObj.getInteger("custom14"));
                }
                if (StringUtil.isExist(rowObj.get("custom15"))) {
                    depotItem.setCustom15(rowObj.getInteger("custom15"));
                }
                if ("盘点单".equals(depotHead.getSubType())) {
                    if (StringUtil.isExist(rowObj.get("tenantId"))) {
                        depotItem.setTenantId(rowObj.getString("tenantId"));
                    }
                }
                if (StringUtil.isExist(rowObj.get("differNumber"))) {
                    depotItem.setDifferNumber(rowObj.getBigDecimal("differNumber"));
                }
                //汇集厂家到货的报损 换货数
                if ("厂家到货".equals(depotHead.getSubType())) {
                    Map<String, Object> custom11Map = new HashMap<>();
                    custom11Map.put("differNumber", depotItem.getDifferNumber());
                    custom11Map.put("custom11", depotItem.getCustom11());
                    custom11Map.put("operNumber", depotItem.getOperNumber());
                    custom11Map.put("basicNumber", depotItem.getBasicNumber());
                    linkIdMap.put(depotItem.getLinkId(), custom11Map);
                }
                //计算返利金额
                if ("采购".equals(depotHead.getSubType()) || "收费确认".equals(depotHead.getSubType())) {
                    BigDecimal rebateProportion = rebateService.getRebateAmount(depotHead.getOrganId(), depotItem.getMaterialId(),
                            depotItem.getOperNumber(), depotHead.getCreateTime());
                    if (rebateProportion !=null && rebateProportion.compareTo(BigDecimal.ZERO)>0){
                        BigDecimal divide = rebateProportion.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal rebatePrice = depotItem.getUnitPrice().multiply(divide);
                        BigDecimal rebateAmount = rebatePrice.multiply(depotItem.getOperNumber());
                        rebateAllAmount=rebateAllAmount.add(rebateAmount);
                        depotItem.setCustom9(rebateAmount);
                        depotItem.setCustom13(1);
                    }
                }
                //出库时判断库存是否充足
                if (((BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType()) && !"采购退货".equals(depotHead.getSubType())) ||
                        ("其它".equals(depotHead.getType()) && "组装单".equals(depotHead.getSubType())&& "普通子件".equals(depotItem.getMaterialType())) ||
                        ("其它".equals(depotHead.getType()) && "拆卸单".equals(depotHead.getSubType())&& "组合件".equals(depotItem.getMaterialType()))||
                        ("其它".equals(depotHead.getType()) && "销售订单".equals(depotHead.getSubType())))
                    ) {
                    BigDecimal stock = materialService.getCurrentStockMapByMaterialId(depotItem.getMaterialId(),depotItem.getDepotId());
                    if ("配送".equals(depotHead.getSubType())) {
                        stock =  materialService.getCurrentStockMapByMaterialId(depotItem.getMaterialId(),depotItem.getAnotherDepotId());
                    }
                    BigDecimal thisBasicNumber = depotItem.getBasicNumber() == null ? BigDecimal.ZERO : depotItem.getBasicNumber();
                    if (!systemConfigService.getMinusStockFlag() && stock.compareTo(thisBasicNumber) < 0) {
                        Material material = materialService.getMaterial(depotItem.getMaterialId());
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_MSG : ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_MSG_US, material.getName()));
                    }
                }
//                if ("其它".equals(depotHead.getSubType()) && StringUtils.isNotEmpty(depotItem.getLinkId())){
//                    updateTakeStockDepotItemStatus(depotItem);
//                }
                this.insertDepotItemWithObj(depotItem);
            }
            if (rebateAllAmount.compareTo(BigDecimal.ZERO)>0){
                depotHead.setCustom12(depotHead.getCustom12() !=null ? depotHead.getCustom12():0);
                depotHead.setCustom10(rebateAllAmount);
                depotHead.setUploadFlag("0");
                depotHeadMapper.updateByPrimaryKeySelective(depotHead);
            }
            //如果关联单据号非空则更新报价状态,此处针对采购订单转报价单
            if ("厂家报价".equals(depotHead.getSubType()) || "直发厂家报价".equals(depotHead.getSubType())) {
                if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
                    //采购订单
                    DepotHead quotation = depotHeadService.getDepotHead(depotHead.getLinkNumber());
                    //报价中
                    quotation.setQuotationStatus("2");
                    quotation.setUploadFlag("0");
                    depotHeadMapper.updateByPrimaryKey(quotation);
                    if ("直发厂家报价".equals(depotHead.getSubType())) {
                        DepotHead zfQuotation = depotHeadService.getDepotHead(quotation.getLinkNumber());
                        //报价中
                        zfQuotation.setQuotationStatus("2");
                        zfQuotation.setUploadFlag("0");
                        depotHeadMapper.updateByPrimaryKey(zfQuotation);
                    }
                }
            }
//            //如果关联单据号非空则更新订单的状态,单据类型：采购入库单或销售出库单或盘点复盘单
//            if (BusinessConstants.SUB_TYPE_PURCHASE.equals(depotHead.getSubType())
//                    || BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType())
//                    || BusinessConstants.SUB_TYPE_REPLAY.equals(depotHead.getSubType())
//                    || "厂家到货".equals(depotHead.getSubType()) || "收费确认".equals(depotHead.getSubType())
//                    || "配送".equals(depotHead.getSubType()) || "验收".equals(depotHead.getSubType())) {
//                if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
//                    //单据状态:是否全部完成 2-全部完成 3-部分完成（针对订单的分批出入库）
//                    String billStatus = getBillStatusByParam(depotHead);
//                    changeBillStatus(depotHead, billStatus);
//                }
//            }
//            //如果关联单据号非空则更新订单的状态,此处针对销售订单转采购订单的场景
//            if (BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())
//                    || "下达采购".equals(depotHead.getSubType())) {
//                if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
//                    String billStatus = getBillStatusByParam(depotHead);
//                    changeBillPurchaseStatus(depotHead, billStatus);
//                }
//            }
            //如果关联单据号非空则更新订单的状态,此处销售退货， 如果是换货的话需要修改订单状态
            if ( "销售退货".equals(depotHead.getSubType()) ) {
                if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
                    String billStatus = getBillStatusByParam(depotHead);
                    changeSaleStatus(depotHead, billStatus);
                }
            }
            if ("厂家到货".equals(depotHead.getSubType())) {
                if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
                    DepotHead depotHeadVo = depotHeadService.getDepotHead(depotHead.getLinkNumber());
                    if (!depotHeadVo.getPurchaseStatus().equals(BusinessConstants.PURCHASE_STATUS_SKIPED)) {
                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_SUB_TYPE_FAIL_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_UB_TYPE_FAIL_MSG : ExceptionConstants.DEPOT_HEAD_UB_TYPE_FAIL_MSG_US, depotHead.getLinkNumber()));
                    } else {
                        List<DepotHead> headList = depotHeadService.getDepotHeadByNumberWithSubType(depotHead.getLinkNumber(), "其它", "下达采购");
                        if (headList != null && headList.size() > 0) {
                            for (DepotHead head : headList) {
                                List<DepotItemVo4WithInfoEx> detailList = getDetailList(head.getId());
                                if (detailList != null && detailList.size() > 0) {
                                    depotHeadService.procurementAcceptance(head, detailList, true, "1830000928627025186d0a2cc488d98cb652f3471f8e3", request, depotIdMap, linkIdMap);
                                } else {
                                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_NOT_ITEM_CODE,
                                            String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_NOT_ITEM_MSG : ExceptionConstants.DEPOT_HEAD_NOT_ITEM_MSG_US, depotHead.getLinkNumber()));
                                }
                            }
                        }
                    }
                }
            }
            if ("采购".equals(depotHead.getSubType()) || "厂家到货".equals(depotHead.getSubType())
                    || "收费确认".equals(depotHead.getSubType()) || "验收".equals(depotHead.getSubType())) {
                if (StringUtil.isNotEmpty(depotHead.getNumber())) {
                    DepotHead depotHeadVo = depotHeadService.getDepotHead(depotHead.getNumber());
                    List<DepotItemVo4WithInfoEx> detailList = getDetailListByCustom11(depotHeadVo.getId());
                    if (detailList != null && detailList.size() > 0) {
                        depotHeadService.purchaseReturn(depotHeadVo, detailList, true, depotHead.getSubType(), request);
                    }
                }
            }
        } else {
            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ROW_FAILED_CODE,
                    String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_ROW_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_ROW_FAILED_MSG_US));
        }
    }

    /**
     * 判断单据的状态
     * 通过数组对比：原单据的商品和商品数量（汇总） 与 分批操作后单据的商品和商品数量（汇总）
     *
     * @param depotHead
     * @return
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public String getBillStatusByParam(DepotHead depotHead) {
        String res = BusinessConstants.BILLS_STATUS_SKIPED;
        //获取原单据的商品和商品数量（汇总）
        List<DepotItemVo4MaterialAndSum> linkList = depotItemMapperEx.getLinkBillDetailMaterialSum(depotHead.getLinkNumber());
        //获取分批操作后单据的商品和商品数量（汇总）
        List<DepotItemVo4MaterialAndSum> batchList = depotItemMapperEx.getBatchBillDetailMaterialSum(depotHead.getLinkNumber(), depotHead.getType(), depotHead.getSubType());
        //将分批操作后的单据的商品和商品数据构造成Map
        Map<String, BigDecimal> materialSumMap = new HashMap<>();
        for (DepotItemVo4MaterialAndSum materialAndSum : batchList) {
            materialSumMap.put(materialAndSum.getMaterialExtendId(), materialAndSum.getOperNumber());
        }
        for (DepotItemVo4MaterialAndSum materialAndSum : linkList) {
            BigDecimal materialSum = materialSumMap.get(materialAndSum.getMaterialExtendId());
            if (materialSum != null) {
                //销售订单要验证销售退货的数量
                BigDecimal salesReturn =BigDecimal.ZERO;
                if (BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())){
                    salesReturn= depotItemMapperEx.getOrderSaleFinishNumber(materialAndSum.getMaterialExtendId(), depotHead.getNumber());
                }
                materialSum= materialSum.subtract(salesReturn);
                if (materialSum.compareTo(materialAndSum.getOperNumber()) < 0) {
                    res = BusinessConstants.BILLS_STATUS_SKIPING;
                }
            } else {
                res = BusinessConstants.BILLS_STATUS_SKIPING;
            }
        }
        return res;
    }

    /**
     * 更新单据状态
     *
     * @param depotHead
     * @param billStatus
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void changeBillStatus(DepotHead depotHead, String billStatus) {
        DepotHead depotHeadOrders = new DepotHead();
        depotHeadOrders.setStatus(billStatus);
        depotHeadOrders.setUploadFlag("0");
        DepotHeadExample example = new DepotHeadExample();
        List<String> linkNumberList = StringUtil.strToStringList(depotHead.getLinkNumber());
        example.createCriteria().andNumberIn(linkNumberList);
        try {
            depotHeadMapper.updateByExampleSelective(depotHeadOrders, example);
        } catch (Exception e) {
            logger.error("异常码[{}],异常提示[{}],异常[{}]",
                    ExceptionConstants.DATA_WRITE_FAIL_CODE, "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DATA_WRITE_FAIL_MSG : ExceptionConstants.DATA_WRITE_FAIL_MSG_US, e);
            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DATA_WRITE_FAIL_MSG : ExceptionConstants.DATA_WRITE_FAIL_MSG_US);
        }
    }

    /**
     * 更新单据状态,此处针对销售订单转采购订单的场景
     *
     * @param depotHead
     * @param billStatus
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void changeBillPurchaseStatus(DepotHead depotHead, String billStatus) {
        DepotHead depotHeadOrders = new DepotHead();
        depotHeadOrders.setPurchaseStatus(billStatus);
        depotHeadOrders.setUploadFlag("0");
        DepotHeadExample example = new DepotHeadExample();
        List<String> linkNumberList = StringUtil.strToStringList(depotHead.getLinkNumber());
        example.createCriteria().andNumberIn(linkNumberList);
        try {
            depotHeadMapper.updateByExampleSelective(depotHeadOrders, example);
        } catch (Exception e) {
            logger.error("异常码[{}],异常提示[{}],异常[{}]",
                    ExceptionConstants.DATA_WRITE_FAIL_CODE, "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DATA_WRITE_FAIL_MSG : ExceptionConstants.DATA_WRITE_FAIL_MSG_US, e);
            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DATA_WRITE_FAIL_MSG : ExceptionConstants.DATA_WRITE_FAIL_MSG_US);
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void changeSaleStatus(DepotHead depotHead, String billStatus) {
        DepotHead depotHeadOrders = new DepotHead();
        depotHeadOrders.setCustom4(billStatus);
        depotHeadOrders.setUploadFlag("0");
        DepotHeadExample example = new DepotHeadExample();
        List<String> linkNumberList = StringUtil.strToStringList(depotHead.getLinkNumber());
        example.createCriteria().andNumberIn(linkNumberList);
        try {
            depotHeadMapper.updateByExampleSelective(depotHeadOrders, example);
        } catch (Exception e) {
            logger.error("异常码[{}],异常提示[{}],异常[{}]",
                    ExceptionConstants.DATA_WRITE_FAIL_CODE, "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DATA_WRITE_FAIL_MSG : ExceptionConstants.DATA_WRITE_FAIL_MSG_US, e);
            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DATA_WRITE_FAIL_MSG : ExceptionConstants.DATA_WRITE_FAIL_MSG_US);
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void deleteDepotItemHeadId(String headerId) throws Exception {
        try {
            //1、查询删除前的单据明细
            List<DepotItem> depotItemList = getListByHeaderId(headerId);
            //2、删除单据明细
            depotItemMapperEx.batchDeleteDepotItemByDepotHeadIds(new String[]{headerId});
//            //3、计算删除之后单据明细中商品的库存
//            for (DepotItem depotItem : depotItemList) {
//                updateCurrentStock(depotItem);
//            }
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public List<DepotItemStockWarningCount> findStockWarningCount(Integer offset, Integer rows, String materialParam, List<String> depotList) {
        List<DepotItemStockWarningCount> list = null;
        try {
            list = depotItemMapperEx.findStockWarningCount(offset, rows, materialParam, depotList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public List<DepotItemStockWarningCount> findInStockWarning(Integer offset, Integer rows, String materialParam, List<String> depotList) {
        List<DepotItemStockWarningCount> list = null;
        try {
            list = depotItemMapperEx.findInStockWarning(offset, rows, materialParam, depotList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int findStockWarningCountTotal(String materialParam, List<String> depotList) {
        int result = 0;
        try {
            result = depotItemMapperEx.findStockWarningCountTotal(materialParam, depotList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int findInStockWarningTotal(String materialParam, List<String> depotList) {
        int result = 0;
        try {
            result = depotItemMapperEx.findInStockWarningTotal(materialParam, depotList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    /**
     * 库存统计-sku
     *
     * @param depotId
     * @param meId
     * @param beginTime
     * @param endTime
     * @return
     */
    public BigDecimal getSkuStockByParam(String depotId, String meId, String beginTime, String endTime) {
        DepotItemVo4Stock stockObj = depotItemMapperEx.getSkuStockByParam(depotId, meId, beginTime, endTime);
        BigDecimal stockSum = BigDecimal.ZERO;
        if (stockObj != null) {
            BigDecimal inTotal = stockObj.getInTotal();
            BigDecimal transfInTotal = stockObj.getTransfInTotal();
            BigDecimal assemInTotal = stockObj.getAssemInTotal();
            BigDecimal disAssemInTotal = stockObj.getDisAssemInTotal();
            BigDecimal outTotal = stockObj.getOutTotal();
            BigDecimal transfOutTotal = stockObj.getTransfOutTotal();
            BigDecimal assemOutTotal = stockObj.getAssemOutTotal();
            BigDecimal disAssemOutTotal = stockObj.getDisAssemOutTotal();
            stockSum = inTotal.add(transfInTotal).add(assemInTotal).add(disAssemInTotal)
                    .subtract(outTotal).subtract(transfOutTotal).subtract(assemOutTotal).subtract(disAssemOutTotal);
        }
        return stockSum;
    }

    /**
     * 库存统计-单仓库
     *
     * @param depotId
     * @param mId
     * @param beginTime
     * @param endTime
     * @return
     */
    public BigDecimal getStockByParam(String depotId, String mId, String beginTime, String endTime) {
        List<String> depotList = new ArrayList<>();
        if (StringUtils.isNotEmpty(depotId)) {
            depotList.add(depotId);
        }else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = null;
            try {
                depotArr = depotService.findDepotByCurrentUser();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (depotArr != null){
                for(Object obj: depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
                //如果有权限的仓库数量太多则提示要选择仓库
                if(depotList.size()>100) {
                    throw new BusinessRunTimeException(ExceptionConstants.REPORT_TWO_MANY_DEPOT_FAILED_CODE,
                            "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.REPORT_TWO_MANY_DEPOT_FAILED_MSG :  ExceptionConstants.REPORT_TWO_MANY_DEPOT_FAILED_MSG_US);
                }
            }
        }
        return getStockByParamWithDepotList(depotList, mId, beginTime, endTime);
    }

    /**
     * 库存统计-多仓库
     *
     * @param depotList
     * @param mId
     * @param beginTime
     * @param endTime
     * @return
     */
    public BigDecimal getStockByParamWithDepotList(List<String> depotList, String mId, String beginTime, String endTime) {
        //初始库存
        BigDecimal initStock = materialService.getInitStockByMidAndDepotList(depotList, mId);
        //盘点复盘后数量的变动
//        BigDecimal stockCheckSum = depotItemMapperEx.getStockCheckSumByDepotList(depotList, mId, beginTime, endTime);
        DepotItemVo4Stock stockObj = depotItemMapperEx.getStockByParamWithDepotList(depotList, mId, beginTime, endTime);
        BigDecimal stockSum = BigDecimal.ZERO;
        if (stockObj != null) {
            BigDecimal inTotal = stockObj.getInTotal();
            BigDecimal transfInTotal = stockObj.getTransfInTotal();
            BigDecimal assemInTotal = stockObj.getAssemInTotal();
            BigDecimal disAssemInTotal = stockObj.getDisAssemInTotal();
            BigDecimal outTotal = stockObj.getOutTotal();
            BigDecimal transfOutTotal = stockObj.getTransfOutTotal();
            BigDecimal assemOutTotal = stockObj.getAssemOutTotal();
            BigDecimal disAssemOutTotal = stockObj.getDisAssemOutTotal();
            stockSum = inTotal.add(transfInTotal).add(assemInTotal).add(disAssemInTotal)
                    .subtract(outTotal).subtract(transfOutTotal).subtract(assemOutTotal).subtract(disAssemOutTotal);
        }
//        return initStock.add(stockCheckSum).add(stockSum);
        return initStock.add(stockSum);
    }


    public void updateCurrentStockFunVo(List<MaterialCurrentStock> materialCurrentStocks) {

        for (MaterialCurrentStock materialCurrentStock : materialCurrentStocks){
            List<String> depotList =new ArrayList<>();
            depotList.add(materialCurrentStock.getDepotId());
            materialCurrentStock.setCurrentNumber(getStockByParamWithDepotList(depotList, materialCurrentStock.getMaterialId(), "2023-05-18", "2023-05-20"));
            materialCurrentStock.setUploadFlag("0");
        }
        materialCurrentStockMapperEx.updateMaterialCurrentStockList(materialCurrentStocks);
    }

    /**
     * 统计时间段内的入库和出库数量-多仓库
     *
     * @param depotList
     * @param mId
     * @param beginTime
     * @param endTime
     * @return
     */
    public Map<String, BigDecimal> getIntervalMapByParamWithDepotList(List<String> depotList, String mId, String beginTime, String endTime) {
        Map<String, BigDecimal> intervalMap = new HashMap<>();
        BigDecimal inSum = BigDecimal.ZERO;
        BigDecimal outSum = BigDecimal.ZERO;
        //盘点复盘后数量的变动
        BigDecimal stockCheckSum = depotItemMapperEx.getStockCheckSumByDepotList(depotList, mId, beginTime, endTime);
        DepotItemVo4Stock stockObj = depotItemMapperEx.getStockByParamWithDepotList(depotList, mId, beginTime, endTime);
        if (stockObj != null) {
            BigDecimal inTotal = stockObj.getInTotal();
            BigDecimal transfInTotal = stockObj.getTransfInTotal();
            BigDecimal assemInTotal = stockObj.getAssemInTotal();
            BigDecimal disAssemInTotal = stockObj.getDisAssemInTotal();
            inSum = inTotal.add(transfInTotal).add(assemInTotal).add(disAssemInTotal);
            BigDecimal outTotal = stockObj.getOutTotal();
            BigDecimal transfOutTotal = stockObj.getTransfOutTotal();
            BigDecimal assemOutTotal = stockObj.getAssemOutTotal();
            BigDecimal disAssemOutTotal = stockObj.getDisAssemOutTotal();
            outSum = outTotal.add(transfOutTotal).add(assemOutTotal).add(disAssemOutTotal);
        }
        if (stockCheckSum.compareTo(BigDecimal.ZERO) > 0) {
            inSum = inSum.add(stockCheckSum);
        } else {
            //盘点复盘数量为负数代表出库
            outSum = outSum.subtract(stockCheckSum);
        }
        intervalMap.put("inSum", inSum);
        intervalMap.put("outSum", outSum);
        return intervalMap;
    }

    /**
     * @Author: wy
     * @Description: 根据期初单据明细批量更新期初库存
     * @DateTime: 2022/8/4 10:07
     * @Params:
     * @Return
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void updateInitialStock(List<DepotItem> detailList,boolean flag) {
        if (null != detailList && detailList.size() > 0) {
            for (DepotItem depotItem : detailList) {
                //初始库存-先查询再更新
                MaterialInitialStockExample example = new MaterialInitialStockExample();
                example.createCriteria().andMaterialIdEqualTo(depotItem.getMaterialId())
                        .andDepotIdEqualTo(depotItem.getDepotId()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
                List<MaterialInitialStock> materialInitialStocks = materialInitialStockMapper.selectByExample(example);
                if (materialInitialStocks != null && materialInitialStocks.size() > 0) {
                    MaterialInitialStock materialInitialStock = materialInitialStocks.get(0);
                    BigDecimal number =BigDecimal.ZERO;
                    if (flag){
                        number= materialInitialStock.getNumber().add(depotItem.getOperNumber());
                    }else {
                        number= materialInitialStock.getNumber().subtract(depotItem.getOperNumber());
                    }
                    materialInitialStock.setNumber(number);
                    materialInitialStock.setUploadFlag("0");
                    materialInitialStockMapper.updateByPrimaryKeySelective(materialInitialStock);
                } else {
                    MaterialInitialStock materialInitialStock = new MaterialInitialStock();
                    materialInitialStock.setId(IdUtils.getUUID());
                    materialInitialStock.setMaterialId(depotItem.getMaterialId());
                    materialInitialStock.setDepotId(depotItem.getDepotId());
                    materialInitialStock.setNumber(depotItem.getOperNumber());
                    materialInitialStock.setUploadFlag("0");
                    materialInitialStockMapper.insertSelective(materialInitialStock);
                }
            }
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void updateCurrentStockByHeaderId(String headerId,boolean updateFlag) throws Exception {
        DepotItemExample itemExample = new DepotItemExample();
        itemExample.createCriteria().andHeaderIdEqualTo(headerId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotItem> detailList = depotItemMapper.selectByExample(itemExample);
        DepotHead depotHead = depotHeadService.getDepotHeadById(headerId);
        boolean flag=false;
        if ("1".equals(depotHead.getStatus())) {
            flag = true;
        }
        if (BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHead.getType()) && BusinessConstants.SUB_TYPE_INVENTORY.equals(depotHead.getSubType())) {
            updateInitialStock(detailList,flag);
        }
        if (null != detailList && detailList.size() > 0) {
            for (DepotItem depotItem : detailList) {
                int stockFlag=0; //0-无 1-增 2-减
                boolean depotType=false; //false-depotId true-anotherDepotId
                if ("出库".equals(depotHead.getType()) && !"配送".equals(depotHead.getSubType())){
                    if (updateFlag){
                        stockFlag=2;
                    }else {
                        stockFlag=1;
                    }
                }else if ("入库".equals(depotHead.getType()) || "期初库存".equals(depotHead.getSubType())){
                    if (updateFlag){
                        stockFlag=1;
                    }else {
                        stockFlag=2;
                    }
                }else if(("组装单".equals(depotHead.getSubType()) && "组合件".equals(depotItem.getMaterialType()))
                        || ("拆卸单".equals(depotHead.getSubType()) && "普通子件".equals(depotItem.getMaterialType())) ){
                    if (updateFlag){
                        stockFlag=1;
                    }else {
                        stockFlag=2;
                    }
                }else if(("组装单".equals(depotHead.getSubType()) && "普通子件".equals(depotItem.getMaterialType()))
                        || ("拆卸单".equals(depotHead.getSubType()) && "组合件".equals(depotItem.getMaterialType())) ){
                    if (updateFlag){
                        stockFlag=2;
                    }else {
                        stockFlag=1;
                    }
                }else if ("配送".equals(depotHead.getSubType())) {
                    depotType=true;
                    if (updateFlag){
                        stockFlag=2;

                    }else {
                        stockFlag=1;
                    }
                }
                updateCurrentStock(depotItem,stockFlag,depotType);
            }
        }
    }

//    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
//    public void updateCurrentStockByHeaderId(String headerId,boolean updateFlag) throws Exception {
//        DepotItemExample itemExample = new DepotItemExample();
//        itemExample.createCriteria().andHeaderIdEqualTo(headerId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
//        List<DepotItem> detailList = depotItemMapper.selectByExample(itemExample);
//        DepotHead depotHead = depotHeadService.getDepotHeadById(headerId);
//        boolean flag=false;
//        if ("1".equals(depotHead.getStatus())) {
//            flag = true;
//        }
//        if (BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHead.getType()) && BusinessConstants.SUB_TYPE_INVENTORY.equals(depotHead.getSubType())) {
//            updateInitialStock(detailList,flag);
//        }
//        if (null != detailList && detailList.size() > 0) {
//            for (DepotItem depotItem : detailList) {
//                updateCurrentStock(depotItem);
//            }
//        }
//    }

    /**
     * 根据单据明细来批量更新当前库存
     *
     * @param depotItem
     */
//    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
//    public void updateCurrentStock(DepotItem depotItem) {
////        DepotHead depotHead = depotHeadMapper.selectByPrimaryKey(depotItem.getHeaderId());
//        String materialId = depotItem.getMaterialId();
////        if ("验收".equals(depotHead.getSubType())) {
////            Material material = materialMapper.selectByPrimaryKey(depotItem.getMaterialId());
////            materialId = materialService.selectMinimumUnit(material.getColor());
////        }
//        updateCurrentStockFun(materialId, depotItem.getDepotId());
//        if (depotItem.getAnotherDepotId() != null) {
//            updateCurrentStockFun(materialId, depotItem.getAnotherDepotId());
//        }
//    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void updateCurrentStock(DepotItem depotItem,int stockFlag,boolean depotType) {
        Depot depot=null;
        String depotId=null;
        BigDecimal operNumber=BigDecimal.ZERO;
        MaterialCurrentStock materialCurrentStock=null;
        try {
            if (depotType){
                depotId=depotItem.getAnotherDepotId();
            }else {
                depotId=depotItem.getDepotId();
            }
            depot = depotService.getDepot(depotId);
            if (depot !=null){
                materialCurrentStock = systemConfigService.getCurrentStockByIdList(depotItem.getMaterialId(), depotId, depot.getTenantId());
                switch (stockFlag){
                    case 1:
                        operNumber=depotItem.getOperNumber().abs();
                        break;
                    case 2:
                        operNumber= operNumber.subtract(depotItem.getOperNumber().abs());
                        break;
                }
                if (materialCurrentStock !=null ){
                    materialCurrentStock.setCurrentNumber(materialCurrentStock.getCurrentNumber().add(operNumber));
                    materialCurrentStock.setUploadFlag("0");
                    materialCurrentStockMapper.updateByPrimaryKeySelective(materialCurrentStock);
                }else {
                    materialCurrentStock = new MaterialCurrentStock();
                    materialCurrentStock.setMaterialId(depotItem.getMaterialId());
                    materialCurrentStock.setDepotId(depotId);
                    materialCurrentStock.setCurrentNumber(operNumber);
                    materialCurrentStock.setUploadFlag("0");
                    materialCurrentStock.setId(IdUtils.getUUID());
                    materialCurrentStockMapper.insertSelective(materialCurrentStock);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据商品和仓库来更新当前库存
     *
     * @param mId
     * @param dId
     */
    public void updateCurrentStockFun(String mId, String dId) {
        if (mId != null && dId != null) {
            MaterialCurrentStockExample example = new MaterialCurrentStockExample();
            example.createCriteria().andMaterialIdEqualTo(mId).andDepotIdEqualTo(dId)
                    .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<MaterialCurrentStock> list = materialCurrentStockMapper.selectByExample(example);
            MaterialCurrentStock materialCurrentStock = new MaterialCurrentStock();
            materialCurrentStock.setMaterialId(mId);
            materialCurrentStock.setDepotId(dId);
            materialCurrentStock.setCurrentNumber(getStockByParam(dId, mId, null, null));
            materialCurrentStock.setUploadFlag("0");
            if (list != null && list.size() > 0) {
                String mcsId = list.get(0).getId();
                materialCurrentStock.setId(mcsId);
                materialCurrentStockMapper.updateByPrimaryKeySelective(materialCurrentStock);
            } else {
                materialCurrentStock.setId(IdUtils.getUUID());
                materialCurrentStockMapper.insertSelective(materialCurrentStock);
            }
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public BigDecimal getFinishNumber(String meId, String id, String headerId, Unit unitInfo, String materialUnit, String linkType) {
        String linkId = id;
        String goToType = "";
        DepotHead depotHead = depotHeadMapper.selectByPrimaryKey(headerId);
        String linkNumber = depotHead.getNumber(); //订单号
        if ("purchase".equals(linkType)) {
            if (BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())) {
                goToType = BusinessConstants.SUB_TYPE_PURCHASE_ORDER;
            }
        } else {
            if (BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())) {
                goToType = BusinessConstants.SUB_TYPE_PURCHASE;
            }
            if ("厂家直发".equals(depotHead.getSubType())) {
                goToType = "厂家到货";
            }
            if (BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())) {
                goToType = BusinessConstants.SUB_TYPE_SALES;
            }
            if ("配送".equals(depotHead.getSubType())) {
                goToType = "验收";
            }
            if ("销售".equals(depotHead.getSubType())) {
                goToType = "销售退货";
            }
            if ("下达采购".equals(depotHead.getSubType())) {
                goToType = "收费确认";
            }
        }
        BigDecimal count = depotItemMapperEx.getFinishNumber(meId, linkId, linkNumber, goToType);
        return count;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public BigDecimal getNotTenantFinishNumber(String meId, String id, String headerId, Unit unitInfo, String materialUnit, String linkType) {
        String goToType = "";
        DepotHead depotHead = synchronizationTaskMapperEx.selectDepotHeadById(headerId);
        String linkNumber = depotHead.getNumber(); //订单号
        if ("purchase".equals(linkType)) {
            if (BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())) {
                goToType = BusinessConstants.SUB_TYPE_PURCHASE_ORDER;
            }
        } else {
            if ("要货申请".equals(depotHead.getSubType())) {
                goToType = "配送";
            }
            if ("配送".equals(depotHead.getSubType())) {
                goToType = "验收";
            }
        }
        BigDecimal count = depotItemMapperEx.getFinishNumber(meId, id, linkNumber, goToType);
        return count;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public BigDecimal getSaleFinishNumber(String meId, String id, String headerId, Unit unitInfo, String materialUnit, String linkType) {
        String linkId = id;
        String goToType = "";
        DepotHead depotHead = depotHeadMapper.selectByPrimaryKey(headerId);
        String linkNumber = depotHead.getNumber(); //订单号
        if (BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())) {
            goToType = BusinessConstants.SUB_TYPE_SALES;
        }
        //已入库数量
        BigDecimal inCount = depotItemMapperEx.getFinishNumber(meId, linkId, linkNumber, goToType);
        //已入库退货数量
        BigDecimal outCount = depotItemMapperEx.getSaleFinishNumber(meId, linkId, linkNumber);
        BigDecimal count = inCount.subtract(outCount);
        //根据多单位情况进行数量的转换
        if (materialUnit.equals(unitInfo.getOtherUnit()) && unitInfo.getRatio() != 0) {
            count = count.divide(BigDecimal.valueOf(unitInfo.getRatio()), 2, BigDecimal.ROUND_HALF_UP);
        }
        if (materialUnit.equals(unitInfo.getOtherUnitTwo()) && unitInfo.getRatioTwo() != 0) {
            count = count.divide(BigDecimal.valueOf(unitInfo.getRatioTwo()), 2, BigDecimal.ROUND_HALF_UP);
        }
        if (materialUnit.equals(unitInfo.getOtherUnitThree()) && unitInfo.getRatioThree() != 0) {
            count = count.divide(BigDecimal.valueOf(unitInfo.getRatioThree()), 2, BigDecimal.ROUND_HALF_UP);
        }
        return count;
    }

    /**
     * 除去此单据之外的已入库|已出库
     *
     * @param meId
     * @param linkId
     * @param preHeaderId
     * @param currentHeaderId
     * @param unitInfo
     * @param materialUnit
     * @return
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public BigDecimal getRealFinishNumber(String meId, String linkId, String preHeaderId, String currentHeaderId, Unit unitInfo, String materialUnit) {
        String goToType = "";
        DepotHead depotHead = depotHeadMapper.selectByPrimaryKey(preHeaderId);
        String linkNumber = depotHead.getNumber(); //订单号
        if (BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())) {
            goToType = BusinessConstants.SUB_TYPE_PURCHASE;
        }
        if (BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())) {
            goToType = BusinessConstants.SUB_TYPE_SALES;
        }
        if ("厂家直发".equals(depotHead.getSubType())) {
            goToType = "厂家到货";
        }
        if (BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())) {
            goToType = BusinessConstants.SUB_TYPE_SALES;
        }
        if ("配送".equals(depotHead.getSubType())) {
            goToType = "验收";
        }
        if ("销售".equals(depotHead.getSubType())) {
            goToType = "销售退货";
        }
        if ("下达采购".equals(depotHead.getSubType())) {
            goToType = "收费确认";
        }
        BigDecimal count = depotItemMapperEx.getRealFinishNumber(meId, linkId, linkNumber, currentHeaderId, goToType);
        //根据多单位情况进行数量的转换
        if (materialUnit.equals(unitInfo.getOtherUnit()) && unitInfo.getRatio() != 0) {
            count = count.divide(BigDecimal.valueOf(unitInfo.getRatio()), 2, BigDecimal.ROUND_HALF_UP);
        }
        if (materialUnit.equals(unitInfo.getOtherUnitTwo()) && unitInfo.getRatioTwo() != 0) {
            count = count.divide(BigDecimal.valueOf(unitInfo.getRatioTwo()), 2, BigDecimal.ROUND_HALF_UP);
        }
        if (materialUnit.equals(unitInfo.getOtherUnitThree()) && unitInfo.getRatioThree() != 0) {
            count = count.divide(BigDecimal.valueOf(unitInfo.getRatioThree()), 2, BigDecimal.ROUND_HALF_UP);
        }
        return count;
    }

    public List<DepotItemVoBatchNumberList> getBatchNumberList(String name, String depotId, String meId, String batchNumber) {
        return depotItemMapperEx.getBatchNumberList(name, depotId, meId, batchNumber);
    }

    public Long getCountByMaterialAndDepot(String mId, String depotId) {
        return depotItemMapperEx.getCountByMaterialAndDepot(mId, depotId);
    }

    /**
     * @Author: wy
     * @Description: 根据供应商和商品编号查询最近的一条采购记录
     * @DateTime: 2022/8/4 14:28
     * @Params: meId supplierId
     * @Return
     */
    public BigDecimal getItemByHeaderIdAndBarcode(String meId, String supplierId, String materialId) {
        BigDecimal recentPurchase = BigDecimal.ZERO;
        try {
            recentPurchase = depotItemMapperEx.getItemByHeaderIdAndBarcode(meId, supplierId, materialId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return recentPurchase;
    }

    /**
     * @Author: wy
     * @Description: 根据客户和商品编号查询最近的一条采购记录
     * @DateTime: 2022/8/4 14:28
     * @Params: meId supplierId
     * @Return
     */
    public BigDecimal getItemByBarcode(String meId, String supplierId, String materialId) {
        BigDecimal recentPurchase = BigDecimal.ZERO;
        try {
            recentPurchase = depotItemMapperEx.getItemByBarcode(meId, supplierId, materialId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return recentPurchase;
    }

    /**
     * @Author: wy
     * @Description: 获取当前商品的库存预警信息
     * @DateTime: 2022/8/6 15:39
     * @Params:
     * @Return
     */
    public DepotItemStockWarningCount findStockByMaterialId(String materialId, String depotId) {
        DepotItemStockWarningCount count = null;
        try {
            count = depotItemMapperEx.findStockByMaterialId(materialId, depotId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    public BigDecimal getShoppingRunningWaterTotal(String type, String subType, String startTime, String endTime, String orderNumber) throws Exception {
        BigDecimal result = BigDecimal.ZERO;
        try {
            result = depotItemMapperEx.getShoppingRunningWaterTotal(type, subType, startTime, endTime, orderNumber);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;

    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public Map<String, Object> getFinishPosNumber(String meId, String id, String headerId, Unit unitInfo, String materialUnit, String linkType) {
        String linkId = id;
        DepotHead depotHead = depotHeadMapper.selectByPrimaryKey(headerId);
        String linkNumber = depotHead.getNumber(); //订单号

        Map<String, Object> countMap = depotItemMapperEx.posGetFinishNumber(meId, linkId, linkNumber, linkType);
        BigDecimal count = (BigDecimal) countMap.get("basicNumber");
        //根据多单位情况进行数量的转换
        if (materialUnit.equals(unitInfo.getOtherUnit()) && unitInfo.getRatio() != 0) {
            countMap.put("count", count.divide(BigDecimal.valueOf(unitInfo.getRatio()), 2, BigDecimal.ROUND_HALF_UP));
        }
        if (materialUnit.equals(unitInfo.getOtherUnitTwo()) && unitInfo.getRatioTwo() != 0) {
            countMap.put("count", count.divide(BigDecimal.valueOf(unitInfo.getRatioTwo()), 2, BigDecimal.ROUND_HALF_UP));
        }
        if (materialUnit.equals(unitInfo.getOtherUnitThree()) && unitInfo.getRatioThree() != 0) {
            countMap.put("count", count.divide(BigDecimal.valueOf(unitInfo.getRatioThree()), 2, BigDecimal.ROUND_HALF_UP));
        }

        return countMap;
    }

    public void getTakeStockDepotHead(String headerId) throws Exception {
        try {
            DepotHead depotHead = depotHeadService.getDepotHeadById(headerId);
            if ("其它".equals(depotHead.getSubType())) {
                DepotItemExample example = new DepotItemExample();
                example.createCriteria().andHeaderIdEqualTo(headerId)
                        .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
                List<DepotItem> depotItems = depotItemMapper.selectByExample(example);
                if (null != depotItems && depotItems.size() > 0) {
                    for (DepotItem depotItem : depotItems) {
                        if (StringUtils.isNotEmpty(depotItem.getLinkId())) {
                            updateTakeStockDepotItemStatus(depotItem, depotHead.getStatus());
                        }
                    }
                }
            }
            if ("厂家报价".equals(depotHead.getSubType()) || "直发厂家报价".equals(depotHead.getSubType())) {
                if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
                    //采购订单
                    DepotHead quotation = depotHeadService.getDepotHead(depotHead.getLinkNumber());
                    //已被报价调用
                    quotation.setQuotationStatus("1");
                    quotation.setTotalPrice(depotHead.getTotalPrice());
                    quotation.setDiscountLastMoney(depotHead.getDiscountLastMoney());
                    quotation.setUploadFlag("0");
                    quotation.setCustom5(depotHead.getCustom5());
                    depotHeadMapper.updateByPrimaryKey(quotation);
                    //报价明细
                    List<DepotItemVo4WithInfoEx> detailList = getDetailList(depotHead.getId());
//                    BigDecimal totalAmount = BigDecimal.ZERO;
                    BigDecimal amount = BigDecimal.ZERO;
                    if (null != detailList && detailList.size() > 0) {
                        //直发厂家报价itemIdList 11，22
                        List<String> IdList = new ArrayList<>();
                        List<DepotItemVo4WithInfoEx> detailList1 = depotItemMapperEx.getDetailList(quotation.getId());
                        detailList1.forEach(depotItemVo4WithInfoEx -> {
                            IdList.add(depotItemVo4WithInfoEx.getLinkId());
                        });

                        //根据itemId删除采购订单和下达采购的明细 33关联11
                        List<String> meIdList = new ArrayList<>();
                        detailList.forEach(depotItemVo4WithInfoEx -> {
                            meIdList.add(depotItemVo4WithInfoEx.getLinkId());
                        });
                        if (meIdList.size() > 0) {
                            DepotItemExample example = new DepotItemExample();
                            example.createCriteria().andIdNotIn(meIdList).andHeaderIdEqualTo(quotation.getId());
                            List<DepotItem> depotItems = depotItemMapper.selectByExample(example);
                            if (depotItems != null && depotItems.size() > 0) {
                                for (DepotItem depotItem : depotItems) {
                                    BigDecimal operNumber = depotItem.getOperNumber();
                                    BigDecimal unitPrice = depotItem.getUnitPrice();
                                    depotItem.setOperNumber(BigDecimal.ZERO);
                                    depotItem.setBasicNumber(BigDecimal.ZERO);
                                    depotItem.setUnitPrice(BigDecimal.ZERO);
                                    depotItem.setTaxUnitPrice(BigDecimal.ZERO);
                                    depotItem.setAllPrice(BigDecimal.ZERO);
                                    depotItem.setTaxMoney(BigDecimal.ZERO);
                                    depotItem.setTaxLastMoney(BigDecimal.ZERO);
                                    depotItem.setCustom5(depotHead.getCustom5());
                                    depotItem.setCustom6(depotItem.getCustom6().compareTo(BigDecimal.ZERO) > 0 ? depotItem.getCustom6() : operNumber);
                                    depotItem.setCustom7(depotItem.getCustom7().compareTo(BigDecimal.ZERO) > 0 ? depotItem.getCustom7() : unitPrice);
                                    depotItem.setUploadFlag("0");
                                    depotItemMapper.updateByPrimaryKeySelective(depotItem);
                                }
                            }
                        }


                        for (DepotItemVo4WithInfoEx detail : detailList) {
                            //33关联11
                            DepotItem depotItem = depotItemMapper.selectByPrimaryKey(detail.getLinkId());
                            BigDecimal operNumber = depotItem.getOperNumber();
                            BigDecimal unitPrice = depotItem.getUnitPrice();
                            depotItem.setOperNumber(detail.getOperNumber());
                            depotItem.setBasicNumber(detail.getBasicNumber());
                            depotItem.setUnitPrice(detail.getUnitPrice());
                            depotItem.setTaxUnitPrice(detail.getTaxUnitPrice());
                            depotItem.setAllPrice(detail.getAllPrice());
                            depotItem.setTaxMoney(detail.getTaxMoney());
                            depotItem.setTaxLastMoney(detail.getTaxLastMoney());
                            depotItem.setCustom5(depotHead.getCustom5());
                            depotItem.setCustom6(depotItem.getCustom6().compareTo(BigDecimal.ZERO) > 0 ? depotItem.getCustom6() : operNumber);
                            depotItem.setCustom7(depotItem.getCustom7().compareTo(BigDecimal.ZERO) > 0 ? depotItem.getCustom7() : unitPrice);
                            depotItem.setUploadFlag("0");
                            depotItemMapper.updateByPrimaryKeySelective(depotItem);
                            if ("直发厂家报价".equals(depotHead.getSubType())) {
                                //11
                                DepotItem item = depotItemMapper.selectByPrimaryKey(depotItem.getLinkId());
                                BigDecimal itemOperNumber = item.getOperNumber();
                                item.setOperNumber(detail.getOperNumber());
                                item.setBasicNumber(detail.getBasicNumber());
                                amount = detail.getOperNumber().multiply(item.getUnitPrice());
                                item.setAllPrice(amount);
                                BigDecimal taxMoney = new BigDecimal("0.1").multiply(amount);
                                BigDecimal taxUnitPrice = item.getUnitPrice().divide(new BigDecimal("1.1"), 2, BigDecimal.ROUND_HALF_UP);
                                item.setTaxMoney(taxMoney);
                                item.setTaxUnitPrice(taxUnitPrice);
                                item.setTaxLastMoney(amount);
                                item.setCustom6(item.getCustom6().compareTo(BigDecimal.ZERO) > 0 ? item.getCustom6() : itemOperNumber);
                                item.setUploadFlag("0");
                                depotItemMapper.updateByPrimaryKeySelective(item);
                                //删除11 IdList剩下22
                                IdList.remove(item.getId());
//                                totalAmount = totalAmount.add(amount);
                            }
                        }
                        if ("直发厂家报价".equals(depotHead.getSubType())) {
                            DepotHead zfQuotation = depotHeadService.getDepotHead(quotation.getLinkNumber());
                            if (IdList.size() > 0) {
                                //把idList中剩下没被报价的金额和数量清零
                                DepotItemExample zfExample = new DepotItemExample();
                                zfExample.createCriteria().andIdIn(IdList).andHeaderIdEqualTo(zfQuotation.getId());
                                List<DepotItem> depotItems = depotItemMapper.selectByExample(zfExample);
                                if (depotItems != null && depotItems.size() > 0) {
                                    for (DepotItem depotItem : depotItems) {
                                        BigDecimal operNumber = depotItem.getOperNumber();
                                        BigDecimal unitPrice = depotItem.getUnitPrice();
                                        depotItem.setOperNumber(BigDecimal.ZERO);
                                        depotItem.setBasicNumber(BigDecimal.ZERO);
                                        depotItem.setUnitPrice(BigDecimal.ZERO);
                                        depotItem.setTaxUnitPrice(BigDecimal.ZERO);
                                        depotItem.setAllPrice(BigDecimal.ZERO);
                                        depotItem.setTaxMoney(BigDecimal.ZERO);
                                        depotItem.setTaxLastMoney(BigDecimal.ZERO);
                                        depotItem.setCustom6(depotItem.getCustom6().compareTo(BigDecimal.ZERO) > 0 ? depotItem.getCustom6() : operNumber);
                                        depotItem.setCustom7(depotItem.getCustom7().compareTo(BigDecimal.ZERO) > 0 ? depotItem.getCustom7() : unitPrice);
                                        depotItem.setUploadFlag("0");
                                        depotItemMapper.updateByPrimaryKeySelective(depotItem);
                                    }
                                }
                            }
                            //重新查询厂家直发订单的明细总金额
                            BigDecimal totalAmount = depotItemMapperEx.getDetailAllPrice(zfQuotation.getId());
                            //已被报价调用
                            zfQuotation.setQuotationStatus("1");
                            zfQuotation.setTotalPrice(totalAmount);
                            zfQuotation.setDiscountLastMoney(totalAmount);
                            zfQuotation.setUploadFlag("0");
                            depotHeadMapper.updateByPrimaryKey(zfQuotation);
                        }
                    }
                }
            }
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateTakeStockDepotItemStatus(DepotItem depotItem, String status) throws Exception {
        int result = 0;
        try {
            DepotItem stockDepotItem = depotItemMapper.selectByPrimaryKey(depotItem.getLinkId());
            stockDepotItem.setUploadFlag("0");
            if (status.equals("0")) {
                stockDepotItem.setCustom12(0);
            } else {
                stockDepotItem.setCustom12(1);
            }
            result = depotItemMapper.updateByPrimaryKeySelective(stockDepotItem);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public int getTakeStockDepotItemStatus(String headerId) throws Exception {
        int result = 0;
        try {
            DepotItemExample example = new DepotItemExample();
            example.createCriteria().andHeaderIdEqualTo(headerId).andCustom12EqualTo(0)
                    .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<DepotItem> depotItems = depotItemMapper.selectByExample(example);
            if (depotItems != null && depotItems.size() > 0) {
                result = depotItems.size();
            }
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }
    public List<DepotItemVo4WithInfoEx> findRebateDetail(String headerId) throws Exception {
        List<DepotItemVo4WithInfoEx> list = null;
        try {
            list = depotItemMapperEx.findRebateDetail(headerId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public BigDecimal findMaterialCost(String materialId) throws Exception {
        BigDecimal result = BigDecimal.ZERO;
        try {
            result = depotItemMapperEx.findMaterialCost(materialId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;

    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void saveStockTakeDetials(String rows, String headerId, String actionType, HttpServletRequest request, boolean flag) throws Exception {
        //查询单据主表信息
        DepotHead depotHead = depotHeadMapper.selectByPrimaryKey(headerId);
        //删除单据的明细
        deleteDepotItemHeadId(headerId);
        JSONArray rowArr = JSONArray.parseArray(rows);
        Map<String, String> depotIdMap = new HashMap<>();
        Map<String, Map<String, Object>> linkIdMap = new HashMap<>();
        if (null != rowArr && rowArr.size() > 0) {
            for (int i = 0; i < rowArr.size(); i++) {
                DepotItem depotItem = new DepotItem();
                JSONObject rowObj = JSONObject.parseObject(rowArr.getString(i));
                depotItem.setHeaderId(headerId);
                String meId = rowObj.getString("meId");
                if (StringUtils.isEmpty(meId)) {
                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_MEID_EMPTY_CODE,
                            String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_MEID_EMPTY_MSG : ExceptionConstants.MATERIAL_MEID_EMPTY_MSG_US));
                }
                MaterialExtend materialExtend = materialExtendService.getInfoByMeId(meId);
                depotItem.setMaterialId(materialExtend.getMaterialId());
                depotItem.setMaterialExtendId(materialExtend.getId());
                depotItem.setMaterialUnit(rowObj.getString("unit"));
                if (StringUtil.isExist(rowObj.get("batchNumber"))) {
                    depotItem.setBatchNumber(rowObj.getString("batchNumber"));
                }
                if (StringUtil.isExist(rowObj.get("expirationDate"))) {
                    depotItem.setExpirationDate(rowObj.getDate("expirationDate"));
                }
                if (StringUtil.isExist(rowObj.get("sku"))) {
                    depotItem.setSku(rowObj.getString("sku"));
                }
                if (("下达采购".equals(depotHead.getSubType()) || "收费确认".equals(depotHead.getSubType())) && flag) {
                    depotItem.setLinkId(rowObj.getString("id"));
                } else if (StringUtil.isExist(rowObj.get("linkId"))) {
                    depotItem.setLinkId(rowObj.getString("linkId"));
                }
                //以下进行单位换算
                Unit unitInfo = materialService.findUnit(materialExtend.getMaterialId()); //查询计量单位信息
                if (StringUtil.isExist(rowObj.get("operNumber"))) {
                    BigDecimal operNumber = rowObj.getBigDecimal("operNumber");
                    if (operNumber.compareTo(BigDecimal.ZERO) > 0 || "盘点单".equals(depotHead.getSubType())) {
                        depotItem.setOperNumber(operNumber);
                        depotItem.setBasicNumber(operNumber);
                    } else {
                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_NUMBER_ZERO_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_NUMBER_ZERO_MSG : ExceptionConstants.DEPOT_HEAD_NUMBER_ZERO_MSG_US, i + 1));
                    }
                }
                //如果数量+已完成数量>原订单数量，给出预警(判断前提是存在关联订单)
                if (StringUtil.isNotEmpty(depotHead.getLinkNumber()) && !"厂家报价".equals(depotHead.getSubType())
                        && !"直发厂家报价".equals(depotHead.getSubType())
                        && StringUtil.isExist(rowObj.get("preNumber")) && StringUtil.isExist(rowObj.get("finishNumber"))) {
                    if ("add".equals(actionType)) {
                        //在新增模式进行状态赋值
                        BigDecimal preNumber = rowObj.getBigDecimal("preNumber");
                        BigDecimal finishNumber = rowObj.getBigDecimal("finishNumber");
                        if (depotItem.getOperNumber().add(finishNumber).compareTo(preNumber) > 0) {
                            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_CODE,
                                    String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_MSG_US));
                        }
                    } else if ("update".equals(actionType)) {
                        //在更新模式进行状态赋值
                        String unit = rowObj.get("unit").toString();
                        String preHeaderId = depotHeadService.getDepotHead(depotHead.getLinkNumber()).getId();
                        //前一个单据的数量
                        BigDecimal preNumber = getPreItemByHeaderIdAndMaterial(depotHead.getLinkNumber(), depotItem.getMaterialExtendId(), depotItem.getLinkId()).getOperNumber();
                        //除去此单据之外的已入库|已出库
                        BigDecimal realFinishNumber = getRealFinishNumber(depotItem.getMaterialExtendId(), depotItem.getLinkId(), preHeaderId, headerId, unitInfo, unit);
                        if (depotItem.getOperNumber().add(realFinishNumber).compareTo(preNumber) > 0) {
                            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_CODE,
                                    String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_NUMBER_NEED_EDIT_FAILED_MSG_US));
                        }
                    }
                }
                if (StringUtil.isExist(rowObj.get("unitPrice"))) {
                    BigDecimal unitPrice = rowObj.getBigDecimal("unitPrice");
                    depotItem.setUnitPrice(unitPrice);
                }
                if (StringUtil.isExist(rowObj.get("taxUnitPrice"))) {
                    depotItem.setTaxUnitPrice(rowObj.getBigDecimal("taxUnitPrice"));
                }
                if (StringUtil.isExist(rowObj.get("allPrice"))) {
                    depotItem.setAllPrice(rowObj.getBigDecimal("allPrice"));
                }
                if (StringUtil.isExist(rowObj.get("depotId"))) {
                    depotItem.setDepotId(rowObj.getString("depotId"));
                } else {
                    if (!BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())
                            && !BusinessConstants.SUB_TYPE_SALES_ORDER.equals(depotHead.getSubType())
                            && !"要货申请".equals(depotHead.getSubType()) && !"配送".equals(depotHead.getSubType())
                            && !"验收".equals(depotHead.getSubType()) && !"补货申请".equals(depotHead.getSubType())
                            && !"厂家直发".equals(depotHead.getSubType()) && !"下达采购".equals(depotHead.getSubType())
                            && !"厂家到货".equals(depotHead.getSubType()) && !"收费确认".equals(depotHead.getSubType())
                            && !"厂家报价".equals(depotHead.getSubType()) && !"直发厂家报价".equals(depotHead.getSubType())
                            && !"直发销售退货".equals(depotHead.getSubType()) && !"直发采购退货".equals(depotHead.getSubType())
                    ) {
                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_DEPOT_FAILED_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_DEPOT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_DEPOT_FAILED_MSG_US));
                    }
                }
                if (StringUtil.isExist(rowObj.get("taxRate"))) {
                    depotItem.setTaxRate(rowObj.getBigDecimal("taxRate"));
                }
                if (StringUtil.isExist(rowObj.get("taxMoney"))) {
                    depotItem.setTaxMoney(rowObj.getBigDecimal("taxMoney"));
                }
                if (StringUtil.isExist(rowObj.get("taxLastMoney"))) {
                    depotItem.setTaxLastMoney(rowObj.getBigDecimal("taxLastMoney"));
                }
                if (StringUtil.isExist(rowObj.get("mType"))) {
                    depotItem.setMaterialType(rowObj.getString("mType"));
                }
                if (StringUtil.isExist(rowObj.get("remark"))) {
                    depotItem.setRemark(rowObj.getString("remark"));
                }
                if (StringUtil.isExist(rowObj.get("priceNote"))) {
                    depotItem.setPriceNote(rowObj.getString("priceNote"));
                }
                if (StringUtil.isExist(rowObj.get("discountPrice"))) {
                    depotItem.setDiscountPrice(rowObj.getBigDecimal("discountPrice"));
                }
                if (StringUtil.isExist(rowObj.get("discountAllPrice"))) {
                    depotItem.setDiscountAllPrice(rowObj.getBigDecimal("discountAllPrice"));
                }
                if (StringUtil.isExist(rowObj.get("custom1"))) {
                    depotItem.setCustom1(rowObj.getString("custom1"));
                }
                if (StringUtil.isExist(rowObj.get("custom2"))) {
                    depotItem.setCustom2(rowObj.getString("custom2"));
                }
                if (StringUtil.isExist(rowObj.get("custom3"))) {
                    depotItem.setCustom3(rowObj.getString("custom3"));
                }
                if (StringUtil.isExist(rowObj.get("custom4"))) {
                    depotItem.setCustom4(rowObj.getString("custom4"));
                }
                if (StringUtil.isExist(rowObj.get("custom5"))) {
                    depotItem.setCustom5(rowObj.getString("custom5"));
                }
                if (StringUtil.isExist(rowObj.get("custom6"))) {
                    depotItem.setCustom6(rowObj.getBigDecimal("custom6"));
                }
                if (StringUtil.isExist(rowObj.get("custom7"))) {
                    depotItem.setCustom7(rowObj.getBigDecimal("custom7"));
                }
                if (StringUtil.isExist(rowObj.get("custom8"))) {
                    depotItem.setCustom8(rowObj.getBigDecimal("custom8"));
                }
                if (StringUtil.isExist(rowObj.get("custom9"))) {
                    depotItem.setCustom9(rowObj.getBigDecimal("custom9"));
                }
                if (StringUtil.isExist(rowObj.get("custom10"))) {
                    depotItem.setCustom10(rowObj.getBigDecimal("custom10"));
                }
                if (StringUtil.isExist(rowObj.get("custom11"))) {
                    depotItem.setCustom11(rowObj.getInteger("custom11"));
                }
                if (StringUtil.isExist(rowObj.get("custom12"))) {
                    depotItem.setCustom12(rowObj.getInteger("custom12"));
                }
                if (StringUtil.isExist(rowObj.get("custom13"))) {
                    depotItem.setCustom13(rowObj.getInteger("custom13"));
                }
                if (StringUtil.isExist(rowObj.get("custom14"))) {
                    depotItem.setCustom14(rowObj.getInteger("custom14"));
                }
                if (StringUtil.isExist(rowObj.get("custom15"))) {
                    depotItem.setCustom15(rowObj.getInteger("custom15"));
                }
                if (StringUtil.isExist(rowObj.get("tenantId"))) {
                    depotItem.setTenantId(rowObj.getString("tenantId"));
                }
                if (StringUtil.isExist(rowObj.get("differNumber"))) {
                    depotItem.setDifferNumber(rowObj.getBigDecimal("differNumber"));
                }
                //出库时判断库存是否充足
                if (((BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType()) && !"采购退货".equals(depotHead.getSubType())) ||
                        ("其它".equals(depotHead.getType()) && "组装单".equals(depotHead.getSubType())&& "普通子件".equals(depotItem.getMaterialType())) ||
                        ("其它".equals(depotHead.getType()) && "拆卸单".equals(depotHead.getSubType())&& "组合件".equals(depotItem.getMaterialType()))||
                        ("其它".equals(depotHead.getType()) && "销售订单".equals(depotHead.getSubType())))
                ) {
                    BigDecimal stock = materialService.getCurrentStockMapByMaterialId(depotItem.getMaterialId(),depotItem.getDepotId());
                    if ("配送".equals(depotHead.getSubType())) {
                        stock =  materialService.getCurrentStockMapByMaterialId(depotItem.getMaterialId(),depotItem.getAnotherDepotId());
                    }
                    BigDecimal thisBasicNumber = depotItem.getBasicNumber() == null ? BigDecimal.ZERO : depotItem.getBasicNumber();
                    if (!systemConfigService.getMinusStockFlag() && stock.compareTo(thisBasicNumber) < 0) {
                        Material material = materialService.getMaterial(depotItem.getMaterialId());
                        throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_MSG : ExceptionConstants.MATERIAL_STOCK_NOT_ENOUGH_MSG_US, material.getName()));
                    }
                }
                this.insertDepotItemWithObj(depotItem);
            }
        } else {
            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ROW_FAILED_CODE,
                    String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_ROW_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_ROW_FAILED_MSG_US));
        }
    }

    public List<DepotItemVo4WithInfoEx> getListWithBugOrSaleDetail(String materialParam, String billType, String beginTime, String endTime,
                                                             Integer offset, Integer rows,String depotId,List<String> idList) throws Exception {
        List<DepotItemVo4WithInfoEx> resList = new ArrayList<>();
        List<DepotItemVo4WithInfoEx> list = null;
        try {
            list = depotItemMapperEx.getListWithBugOrSaleDetail(materialParam, billType, beginTime, endTime, offset, rows,depotId,idList);
            if (null != list) {
                for (DepotItemVo4WithInfoEx dh : list) {
                    if (dh.getOperTime() != null) {
                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    }

                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public int getListWithBugOrSaleDetailCount(String materialParam, String billType, String beginTime, String endTime,String depotId,List<String> idList) throws Exception {
        int result = 0;
        try {
            result = depotItemMapperEx.getListWithBugOrSaleDetailCount(materialParam, billType, beginTime, endTime,depotId,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotItem> getStockCountDetailList(String beginTime, String endTime) throws Exception {
        List<DepotItem> result = null;
        try {
            result = depotItemMapperEx.getStockCountDetailList(beginTime, endTime);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotItemVo4WithInfoEx> saleOut(String materialParam, String billType, String beginTime, String endTime,
                                                             Integer offset, Integer rows,String depotId,List<String> idList) throws Exception {
        List<DepotItemVo4WithInfoEx> list = null;
        try {
            list = depotItemMapperEx.getListWithBugOrSale(materialParam, billType, beginTime, endTime, offset, rows,depotId,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public int saleOutCount(String materialParam, String billType, String beginTime, String endTime,String depotId,List<String> idList) throws Exception {
        int result = 0;
        try {
            result = depotItemMapperEx.getListWithBugOrSaleCount(materialParam, billType, beginTime, endTime,depotId,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }
}
